﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CongregacaoOs.Data;
using CongregacaoOs.Business;
using System.Web.Security;
using System.Text;


namespace CongregacaoOs.WebForm.Cadastros
{
    public partial class Servo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["DadosGerais"] == null) Response.Redirect("~/Cadastros/Account/Login.aspx");

            if (Session["TipoUsuario"].ToString() == "Local") Response.Redirect("~/Cadastros/Home.aspx");

            if (Session["TipoUsuario"].ToString() == "Regional") ResetPasswordPanel.Visible = true;
            


            Page.Form.DefaultButton = btnBuscar.UniqueID;

            if (!IsPostBack)
            {

                AtualizarGridView();
                AtualizarDropDowListRegional();
                AtualizarDropDowListRoles();
                AtualizarDropRegionalFiltro();
            }


        }

        public void AtualizarGridView()
        {
            ccPessoaBus bus = new ccPessoaBus();
            ccPessoa ent = new ccPessoa();

            ent.nome = txtBuscarNome.Text.Trim();
            ent.idRegional = dropRegionalFiltro.SelectedValue != "" ? Convert.ToInt32(dropRegionalFiltro.SelectedValue) : 0;
            ent.idDistrital = dropDistritalFiltro.SelectedValue != "" ? Convert.ToInt32(dropDistritalFiltro.SelectedValue) : 0;
            ent.idAdm = dropAdmFiltro.SelectedValue != "" ? Convert.ToInt32(dropAdmFiltro.SelectedValue) : 0;
            ent.idSetor = dropSetorFiltro.SelectedValue != "" ? Convert.ToInt32(dropSetorFiltro.SelectedValue) : 0;

            if (radioStatusUsu.SelectedValue != "0")
                ent.status = radioStatusUsu.SelectedValue == "1" ? true : false;

            gvServo.DataSource = bus.PessoaSelect(ent);
            gvServo.DataBind();
        }

        protected void radioStatusUsu_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarGridView();
        }

        public void AtualizarDropDowListRegional(int aID = 0)
        {
            ccRegionalBus bus = new ccRegionalBus();
            ccRegional ent = new ccRegional();
            ent.idRegional = 0;
            ent.nome = "";
            ent.idEstado = 0;
            ent.idPais = 0;
            dropRegional.DataSource = bus.RegionalSelect(ent);
            dropRegional.DataBind();
        }

        public void AtualizarDropDowListDistrital()
        {
            ccDistritalBus bus = new ccDistritalBus();
            ccDistrital ent = new ccDistrital();

            if (dropRegional.SelectedValue != "")
            {
                ent.idRegional = Convert.ToInt32(dropRegional.SelectedValue);
                dropDistrital.DataSource = bus.DistritalSelect(ent);
                dropDistrital.DataBind();
            }
            else
            {
                dropDistrital.Items.Clear();
                dropSetor.Items.Clear();
                dropCargo.Items.Clear();
                dropAdministracao.Items.Clear();
                dropCidade.Items.Clear();
                dropComum.Items.Clear();
            }
        }

        public void AtualizarDropDowListCidade(int aID = 0)
        {
            if (dropRegional.SelectedValue != "" && dropDistrital.SelectedValue != "" && dropAdministracao.SelectedValue != "")
            {
                ccCidadeBus bus = new ccCidadeBus();
                ccCidade ent = new ccCidade();
                ent.idRegional = aID;


                ent.idRegional = dropRegional.SelectedValue != "" ? Convert.ToInt32(dropRegional.SelectedValue) : 0;

                ent.idDistrital = dropDistrital.SelectedValue != "" ? Convert.ToInt32(dropDistrital.SelectedValue) : 0;

                dropCidade.DataSource = bus.CidadeSelectComboBox(ent);
                dropCidade.DataBind();
            }
            else
            {
                dropCidade.Items.Clear();
                dropComum.Items.Clear();
            }
        }

        public void AtualizarDropDowListIgreja()
        {
            ccIgrejaBus bus = new ccIgrejaBus();
            ccIgreja ent = new ccIgreja();

            if (dropCidade.SelectedValue != "")
            {
                ent.idCidade = dropCidade.SelectedValue != "" ? Convert.ToInt32(dropCidade.SelectedValue) : 0;
                ent.nome = "";
                ent.numero = "";
                ent.idDistrital = 0;
                dropComum.DataSource = bus.IgrejaSelect(ent);
                dropComum.DataBind();
            }
            else
            {
                dropComum.Items.Clear();
            }

        }

        public void AtualizarDropDowListRoles()
        {
            dropRoles.DataSource = Roles.GetAllRoles();
            dropRoles.DataBind();

            if (Session["TipoUsuario"].ToString() != "Regional")
            {
                ListItem item = dropRoles.Items.FindByText("Regional");
                dropRoles.Items.Remove(item);
            }
        }

        public void AtualizarDropDowListCargo()
        {
            if (dropSetor.SelectedValue != "")
            {
                ccSetorCargosBus bus = new ccSetorCargosBus();
                ccSetorCargos ent = new ccSetorCargos();
                List<ccSetorCargosSelect_Result> listResult = new List<ccSetorCargosSelect_Result>();
                if (dropSetor.SelectedValue != "0")
                    listResult = bus.SetorCargosSelect(Convert.ToInt32(dropSetor.SelectedValue));

                if (listResult != null)
                {
                    dropCargo.DataSource = listResult;
                    dropCargo.DataBind();
                }
                else
                {
                    dropCargo.Items.Clear();
                }
            }
            else { dropCargo.Items.Clear(); }
        }

        public void AtualizarDropDowListSetor()
        {
            ccSetorBus bus = new ccSetorBus();
            ccSetor ent = new ccSetor();

            if (dropAdministracao.SelectedValue != "")
            {
                int aIdAdm = dropAdministracao.SelectedValue != "" ? Convert.ToInt32(dropAdministracao.SelectedValue) : 0;
                dropSetor.DataSource = bus.SetorSelectByAdm(aIdAdm);
                dropSetor.DataBind();
            }
            else
            {
                dropSetor.Items.Clear();
                dropCargo.Items.Clear();
            }

        }


        public void AtualizarDropDowListAdm()
        {
            ccAdmBus bus = new ccAdmBus();
            ccAdm ent = new ccAdm();

            if (dropRegional.SelectedValue != "" && dropDistrital.SelectedValue != "")
            {
                ent.idRegional = dropRegional.SelectedValue != "" ? Convert.ToInt32(dropRegional.SelectedValue) : 0;
                ent.idDistrital = dropDistrital.SelectedValue != "" ? Convert.ToInt32(dropDistrital.SelectedValue) : 0;

                dropAdministracao.DataSource = bus.AdmSelect(ent);
                dropAdministracao.DataBind();
            }
            else
            {
                dropAdministracao.Items.Clear();
                dropSetor.Items.Clear();
                dropCargo.Items.Clear();
                dropCidade.Items.Clear();
                dropComum.Items.Clear();
            }
        }

        #region Filtros
        public void AtualizarDropRegionalFiltro()
        {
            using (ccRegionalBus bus = new ccRegionalBus())
            {
                ccRegional ent = new ccRegional();
                ent.idEstado = 0;
                ent.nome = "";
                ent.idPais = 0;
                dropRegionalFiltro.DataSource = bus.RegionalSelect(ent);
                dropRegionalFiltro.DataBind();
            }

        }

        public void AtualizarDropDistritalFiltro()
        {
            using (ccDistritalBus bus = new ccDistritalBus())
            {
                ccDistrital ent = new ccDistrital();

                if (dropRegionalFiltro.SelectedValue != "")
                {
                    ent.idRegional = Convert.ToInt32(dropRegionalFiltro.SelectedValue);
                    dropDistritalFiltro.DataSource = bus.DistritalSelect(ent);
                    dropDistritalFiltro.DataBind();
                }
                else
                {
                    dropDistritalFiltro.Items.Clear();
                    dropAdmFiltro.Items.Clear();
                    dropSetorFiltro.Items.Clear();
                }

            }
        }

        public void AtualizarDropAdmFiltro()
        {
            if (dropRegionalFiltro.SelectedValue != "" && dropDistritalFiltro.SelectedValue != "")
            {
                using (ccAdmBus bus = new ccAdmBus())
                {

                    ccAdm ent = new ccAdm();

                    ent.idRegional = dropRegionalFiltro.SelectedValue != "" ? Convert.ToInt32(dropRegionalFiltro.SelectedValue) : 0;
                    ent.idDistrital = dropDistritalFiltro.SelectedValue != "" ? Convert.ToInt32(dropDistritalFiltro.SelectedValue) : 0;

                    dropAdmFiltro.DataSource = bus.AdmSelect(ent);
                    dropAdmFiltro.DataBind();

                }

            }
            else
            {
                dropAdmFiltro.Items.Clear();
                dropSetorFiltro.Items.Clear();
            }
        }

        public void AtualizarDropSetorFiltro()
        {
            if (dropAdmFiltro.SelectedValue == "")
            {
                dropSetorFiltro.Items.Clear();
                return;
            }

            using (ccSetorBus bus = new ccSetorBus())
            {
                ccSetor ent = new ccSetor();

                if (dropAdmFiltro.SelectedValue != "")
                {
                    dropSetorFiltro.DataSource = bus.SetorSelectByAdm(Convert.ToInt32(dropAdmFiltro.SelectedValue));
                    dropSetorFiltro.DataBind();

                }
                else
                {
                    dropSetorFiltro.Items.Clear();
                }
            }
        }
        #endregion

        protected void dropCidade_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDowListIgreja();
        }

        protected void gvServo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EDITAR" || e.CommandName == "EXCLUIR")
            {
                GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);

                int index = row.RowIndex;

                HiddenField hdIdPessoa = (gvServo.Rows[index].FindControl("hdIdPessoa") as HiddenField);
                HiddenField hdUserName = (gvServo.Rows[index].FindControl("hdUserName") as HiddenField);
                hdID.Value = hdIdPessoa.Value;


                if (e.CommandName == "EDITAR")
                {

                    HiddenField hdServo = (gvServo.Rows[index].FindControl("hdServo") as HiddenField);
                    HiddenField hdStatus = (gvServo.Rows[index].FindControl("hdStatus") as HiddenField);
                    HiddenField hdFone = (gvServo.Rows[index].FindControl("hdFone") as HiddenField);

                    Session["UserStatus"] = hdStatus.Value;

                    HiddenField hdCelular = (gvServo.Rows[index].FindControl("hdCelular") as HiddenField);
                    HiddenField hdEmail = (gvServo.Rows[index].FindControl("hdEmail") as HiddenField);
                    HiddenField hdRegional = (gvServo.Rows[index].FindControl("hdRegional") as HiddenField);
                    HiddenField hdDistrital = (gvServo.Rows[index].FindControl("hdDistrital") as HiddenField);

                    HiddenField hdCidade = (gvServo.Rows[index].FindControl("hdCidade") as HiddenField);
                    HiddenField hdComum = (gvServo.Rows[index].FindControl("hdComum") as HiddenField);

                    HiddenField hdRoleName = (gvServo.Rows[index].FindControl("hdRoleName") as HiddenField);
                    Session["RoleOld"] = hdRoleName.Value;
                    HiddenField hdCargo = (gvServo.Rows[index].FindControl("hdCargo") as HiddenField);

                    HiddenField hdQuestion = (gvServo.Rows[index].FindControl("hdQuestion") as HiddenField);
                    HiddenField hdSetor = (gvServo.Rows[index].FindControl("hdSetor") as HiddenField);

                    HiddenField hdAdm = (gvServo.Rows[index].FindControl("hdAdm") as HiddenField);


                    txtNome.Text = hdServo.Value.ToString();
                    checkAtivo.Checked = Convert.ToBoolean(hdStatus.Value);
                    txtTelefone.Text = hdFone.Value.ToString();
                    txtCelular.Text = hdCelular.Value.ToString();
                    txtEmail.Text = hdEmail.Value.ToString();


                    AtualizarDropDowListRegional();
                    if (hdRegional.Value != "" && dropRegional.Items.FindByText(hdRegional.Value) != null)
                        dropRegional.Items.FindByText(hdRegional.Value).Selected = true;


                    AtualizarDropDowListDistrital();
                    if (hdDistrital.Value != "" && dropDistrital.Items.FindByText(hdDistrital.Value) != null)
                        dropDistrital.Items.FindByText(hdDistrital.Value).Selected = true;


                    AtualizarDropDowListAdm();
                    if (hdAdm.Value != "" && dropAdministracao.Items.FindByText(hdAdm.Value) != null)
                        dropAdministracao.Items.FindByText(hdAdm.Value).Selected = true;


                    AtualizarDropDowListSetor();
                    if (hdSetor.Value != "" && dropSetor.Items.FindByText(hdSetor.Value) != null)
                        dropSetor.Items.FindByText(hdSetor.Value).Selected = true;


                    AtualizarDropDowListCargo();
                    if (hdCargo.Value != "" && dropCargo.Items.FindByText(hdCargo.Value) != null)
                        dropCargo.Items.FindByText(hdCargo.Value).Selected = true;


                    txtUsuario.Text = hdUserName.Value;
                    //txtSenha.Text = "DDDDDDD";
                    txtSenha.Enabled = false;
                    //txtSenhaConfirm.Text = "DDDDDDD";
                    txtSenhaConfirm.Enabled = false;
                    txtUsuario.Enabled = false;

                    txtLembrete.Text = hdQuestion.Value;

                    AtualizarDropDowListRoles();
                    if (hdRoleName.Value != "" && dropRoles.Items.FindByText(hdRoleName.Value) != null)
                        dropRoles.Items.FindByText(hdRoleName.Value).Selected = true;


                    AtualizarDropDowListCidade();
                    if (hdCidade.Value != "" && dropCidade.Items.FindByText(hdCidade.Value) != null)
                        dropCidade.Items.FindByText(hdCidade.Value).Selected = true;

                    AtualizarDropDowListIgreja();
                    if (hdComum.Value != "" && dropComum.Items.FindByText(hdComum.Value) != null)
                        dropComum.Items.FindByText(hdComum.Value).Selected = true;

                    hfIndexAccordion.Value = "1";

                }
                else if (e.CommandName == "EXCLUIR")
                {
                    try
                    {
                        ccPessoaBus bus = new ccPessoaBus();
                        bus.PessoaDelete(Convert.ToInt32(hdID.Value));
                        Membership.DeleteUser(hdUserName.Value.ToString());
                    }
                    catch (Exception error)
                    {

                        throw new Exception("Erro:" + error.Message);
                    }
                }
            }


            AtualizarGridView();
        }

        protected void gvServo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            AtualizarGridView();
            gvServo.PageIndex = e.NewPageIndex;
            gvServo.DataBind();
        }

        protected void dropRegional_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDowListDistrital();
        }

        protected void gvServo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton imgEditar = (e.Row.FindControl("imgEditar") as ImageButton);
                imgEditar.CommandArgument = e.Row.RowIndex.ToString();

                ImageButton imgDelete = (e.Row.FindControl("imgDelete") as ImageButton);
                imgDelete.CommandArgument = e.Row.RowIndex.ToString();

                imgDelete.Attributes.Add("onclick", "javascript:return " +
                        "confirm('Confirmar exclusão do registro: " +
                        DataBinder.Eval(e.Row.DataItem, "Servo") + "?')");

                ImageButton imgStatus = (e.Row.FindControl("imgStatus") as ImageButton);

                switch (imgStatus.CommandArgument)
                {
                    case "True":
                        imgStatus.ImageUrl = @"~\Images\User\ON.png";
                        imgStatus.ToolTip = "Ativo";
                        break;
                    case "False":
                        imgStatus.ImageUrl = @"~\Images\User\OFF.png";
                        imgStatus.ToolTip = "Inativo";
                        break;
                }

            }
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {

            if (dropAdministracao.SelectedValue == "" || dropSetor.SelectedValue == "" || dropCargo.SelectedValue == "" || dropCidade.SelectedValue == "" || dropComum.SelectedValue == "")
            {
                MessageWindow.Texto = "Os campos Administração, Setor e Cargo são obrigatórios";
                MessageWindow.MessageType = false;
                MessageWindow.ShowWindow();
                return;
            }



            ccPessoaBus bus = new ccPessoaBus();
            ccPessoa ent = new ccPessoa();
            GetServantFeatures1_Result dadosGerais = new GetServantFeatures1_Result();


            ent.nome = txtNome.Text.Trim();
            ent.email = txtEmail.Text.Trim();
            ent.celular = txtCelular.Text.Trim();
            ent.fone = txtTelefone.Text.Trim();
            ent.status = checkAtivo.Checked;

            ent.idRegional = dropRegional.SelectedValue != "" ? Convert.ToInt32(dropRegional.SelectedValue) : 0;
            ent.idDistrital = dropDistrital.SelectedValue != "" ? Convert.ToInt32(dropDistrital.SelectedValue) : 0;
            ent.idCidade = dropCidade.SelectedValue != "" ? Convert.ToInt32(dropCidade.SelectedValue) : 0;
            ent.idComum = dropComum.SelectedValue != "" ? Convert.ToInt32(dropComum.SelectedValue) : 0;
            ent.idCargo = dropCargo.SelectedValue != "" ? Convert.ToInt32(dropCargo.SelectedValue) : 0;
            ent.idSetor = dropSetor.SelectedValue != "" ? Convert.ToInt32(dropSetor.SelectedValue) : 0;
            ent.idAdm = dropAdministracao.SelectedValue != "" ? Convert.ToInt32(dropAdministracao.SelectedValue) : 0;
            if (txtLembrete.Text == "") txtLembrete.Text = ".";

            if (hdID.Value == "")
            {
                if (txtSenha.Text.Trim() == txtSenhaConfirm.Text.Trim())
                {



                    MembershipCreateStatus status;
                    MembershipUser novoUsuario = Membership.CreateUser(txtUsuario.Text.Trim(), txtSenha.Text.Trim(), txtEmail.Text.Trim(), txtLembrete.Text.Trim(), txtLembrete.Text.Trim(), checkAtivo.Checked, out status);
                    switch (status)
                    {
                        case MembershipCreateStatus.Success:
                            try
                            {
                                Roles.AddUserToRole(txtUsuario.Text.Trim(), dropRoles.Text);
                                ent.idUsuario = (Guid)novoUsuario.ProviderUserKey;
                            }
                            catch (Exception erro)
                            {
                                MessageWindow.MessageType = false;
                                MessageWindow.Texto = "Ocorreu um erro ao relacionar o usuário como o seu grupo. Exclua o usuário e tente novamente";
                                MessageWindow.ShowWindow();
                                return;
                            }
                            break;
                        case MembershipCreateStatus.DuplicateUserName:
                            MessageWindow.MessageType = false;
                            MessageWindow.Texto = "Já existe um usuário com esse username.";
                            MessageWindow.ShowWindow();
                            break;
                        case MembershipCreateStatus.DuplicateEmail:
                            MessageWindow.MessageType = false;
                            MessageWindow.Texto = "Este email já esta cadastrado na base.";
                            MessageWindow.ShowWindow();
                            break;
                        case MembershipCreateStatus.InvalidEmail:
                            MessageWindow.MessageType = false;
                            MessageWindow.Texto = "Este endereço de email é inválido.";
                            MessageWindow.ShowWindow();
                            break;
                        case MembershipCreateStatus.InvalidAnswer:
                            MessageWindow.MessageType = false;
                            MessageWindow.Texto = "Resposta de segurança é invalida.";
                            MessageWindow.ShowWindow();
                            break;
                        case MembershipCreateStatus.InvalidPassword:
                            MessageWindow.MessageType = false;
                            MessageWindow.Texto = "A senha informada é invalida, tente novamente.";
                            MessageWindow.ShowWindow();
                            break;
                        default:
                            MessageWindow.MessageType = false;
                            MessageWindow.Texto = "Ocorreu um erro desconhecido, o usuário não foi criado.";
                            MessageWindow.ShowWindow();
                            break;
                    }
                }
                else
                {
                    MessageWindow.MessageType = false;
                    MessageWindow.Texto = "Verifique as senhas.Pois as informações são diferentes.";
                    MessageWindow.ShowWindow();
                    return;

                }
            }
            else
            {
                MembershipUser AlterUser = Membership.GetUser(txtUsuario.Text.Trim());
                ent.idUsuario = (Guid)AlterUser.ProviderUserKey;
                ent.idPessoa = Convert.ToInt32(hdID.Value);
                Roles.RemoveUserFromRole(txtUsuario.Text.Trim(), Session["RoleOld"].ToString());
                Roles.AddUserToRole(txtUsuario.Text.Trim(), dropRoles.Text);

            }


            try
            {
                hfIndexAccordion.Value = "0";
                bus.PessoaSaveOrUpdate(ent, txtLembrete.Text.Trim());

                if (hdID.Value != "")
                if (checkAtivo.Checked == true && checkAtivo.Checked != Convert.ToBoolean(Session["UserStatus"].ToString()))
                {
                    try
                    {
                        using (ccSendEmail busEmail = new ccSendEmail())
                        {
                            using (ClassEmail email = new ClassEmail())
                            {
                                email.Assunto = @"Portal de O.S - Usuário ativado com sucesso!";
                                email.Menssagem ="<HEAD>" +
                               "<TITLE>Regional Ribeirão Preto</TITLE>" +
                               "<STYLE TYPE='text/css'>" +
                               "* { margin: 0 auto; width:800px; padding: 0px; }" +
                               "body { font-size: 80%; font-family: 'Lucinda Grande', Verdana, Sans-Serif; margin: 0 auto; }" +
                               "h1 { font-size: 150%; font-weight: bold; color: white; }" +
                               "h2 { font-size: 110%; font-weight: bold; margin: 0 0 10px 20px; }" +
                               "p { font-size: 100%; line-height: 150%; margin: 20px; }" +
                               ".header { padding: 10px; border: 1px solid #000000; background-color: #336699; height: 40px; color: #EEEEEE; width: 100%; }" +
                               ".content { margin-left: 25px; }" +
                               "th { text-align: left; font-weight: bold; padding-right: 10px; }"+
                               ".footer { padding: 10px; border: 1px solid #000000; background-color: #336699; height: 20px; color: #EEEEEE; width: 100%; }" +
                               "</STYLE>" +
                               "</HEAD>" +
                               "<BODY>" +
                               "<TABLE>" +
                               "<TR><TD class='header'>" +
                               "<H1>Ativação de Usuário</H1>" +
                               "</TD></TR>" +
                               "<TR><TD>" +
                               "<P>" +
                                      "<br/><b>Caro Ir.: </b>" + txtNome.Text + "<br />" +
                                      "<b>Usuário:</b> " + txtUsuario.Text + " <br />" +
                                      "<b>O Seu usuário foi ativado com sucesso!</b> <br />" +
                                      "<a href='http://www.ccbos.com.br'>Clique aqui para acessar portal de O.S!</a> " +
                                      "<br/><br/><b>Não responda este e-mail</b>" +
                               "</P>" +
                               "</TD></TR>" +
                               "<TR><TD class='footer'>" +
                               "Grupo de Apoio Regional Ribeirão Preto" +
                               "</TD></TR>" +
                               "</TABLE>" +
                               "</BODY>" + 
                               "</HTML>";

                                ccPessoa entPes = new ccPessoa();
                                ccPessoaBus busPes = new ccPessoaBus();

                                if (txtEmail.Text != "")
                                {
                                    email.ListofDestinatario.Add("diasboldrin@gmail.com");
                                    email.ListofDestinatario.Add("infotrans@terra.com.br");
                                    email.ListofDestinatario.Add(txtEmail.Text);
                                    busEmail.SendMail(email);
                                }



                            }
                        }
                    }
                    catch (Exception)
                    {
                        MessageWindow.MessageType = false;
                        MessageWindow.Texto = "Houve um erro ao enviar o e-mail. O Usuário não foi avisado por e-mail. ";
                        MessageWindow.ShowWindow();
                        return;
                    }
                }

                Session["UserStatus"] = "";

                AtualizarGridView();
                Functions.LimparCampos(this);
                AlinharCampos();


                MessageWindow.MessageType = true;
                MessageWindow.Texto = "Usuário salvo com sucesso!";
                MessageWindow.ShowWindow();

                dadosGerais = (GetServantFeatures1_Result)Session["DadosGerais"];
                if (dadosGerais.idPessoa != 0 && dadosGerais.idPessoa == ent.idPessoa)
                {
                    Response.Redirect(@"~\Cadastros\Account\Login.aspx");
                }
            }
            catch (Exception)
            {

                throw;
            }



        }


        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            AtualizarGridView();
        }

        protected void btnAdicionarNovo_Click(object sender, EventArgs e)
        {
            hfIndexAccordion.Value = "1";
            AtualizarDropDowListRegional();
            AtualizarDropDowListDistrital();
            txtSenha.Enabled = true;
            txtSenhaConfirm.Enabled = true;
            txtUsuario.Enabled = true;
            hdID.Value = "";
            AlinharCampos();
            Session["UserStatus"] = "";
        }

        protected void btnVoltar_Click(object sender, EventArgs e)
        {
            hfIndexAccordion.Value = "0";
            hdID.Value = "";
            Session["UserStatus"] = "";
            AlinharCampos();
        }

        protected void dropSetor_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDowListCargo();
        }

        protected void dropDistrital_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDowListAdm();
        }

        public void AlinharCampos()
        {
            dropDistritalFiltro.Items.Clear();
            dropAdmFiltro.Items.Clear();
            dropSetorFiltro.Items.Clear();

            Functions.LimparCampos(this);

            if (dropCargo.Items.Count > 0) dropCargo.SelectedIndex = 0;
            if (dropRegional.Items.Count > 0) dropRegional.SelectedIndex = 0;
            if (dropDistrital.Items.Count > 0) dropDistrital.SelectedIndex = 0;
            if (dropCidade.Items.Count > 0) dropCidade.SelectedIndex = 0;
            if (dropComum.Items.Count > 0) dropComum.SelectedIndex = 0;
            if (dropRoles.Items.Count > 0) dropRoles.SelectedIndex = 0;

            if (dropSetor.Items.Count > 0) dropSetor.SelectedIndex = 0;
            if (dropCargo.Items.Count > 0) dropCargo.SelectedIndex = 0;

            if (dropAdministracao.Items.Count > 0) dropAdministracao.SelectedIndex = 0;
            checkAtivo.Checked = false;
            AtualizarGridView();
        }

        protected void dropAdministracao_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDowListSetor();
            AtualizarDropDowListCidade();
        }

        protected void dropRegional_DataBound(object sender, EventArgs e)
        {
            dropRegional.Items.Insert(0, new ListItem("Escolha a Regional...", String.Empty));
        }

        protected void dropDistrital_DataBound(object sender, EventArgs e)
        {
            dropDistrital.Items.Insert(0, new ListItem("Escolha a Distrital...", String.Empty));
        }

        protected void dropAdministracao_DataBound(object sender, EventArgs e)
        {
            dropAdministracao.Items.Insert(0, new ListItem("Escolha a Administração...", String.Empty));
        }

        protected void dropSetor_DataBound(object sender, EventArgs e)
        {
            dropSetor.Items.Insert(0, new ListItem("Escolha o Setor...", String.Empty));
        }

        protected void dropCargo_DataBound(object sender, EventArgs e)
        {
            dropCargo.Items.Insert(0, new ListItem("Escolha o Cargo...", String.Empty));
        }

        protected void dropCidade_DataBound(object sender, EventArgs e)
        {
            dropCidade.Items.Insert(0, new ListItem("Escolha a Cidade...", String.Empty));
        }

        protected void dropComum_DataBound(object sender, EventArgs e)
        {
            dropComum.Items.Insert(0, new ListItem("Escolha a Comum...", String.Empty));
        }

        protected void dropRegionalFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDistritalFiltro();
            AtualizarGridView();
        }

        protected void dropRegionalFiltro_DataBound(object sender, EventArgs e)
        {
            dropRegionalFiltro.Items.Insert(0, new ListItem("Escolha a Regional...", String.Empty));
        }

        protected void dropDistritalFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropAdmFiltro();
            AtualizarGridView();
        }
        protected void dropDistritalFiltro_DataBound(object sender, EventArgs e)
        {
            dropDistritalFiltro.Items.Insert(0, new ListItem("Escolha a Distrital...", String.Empty));
        }

        protected void dropAdmFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropSetorFiltro();
            AtualizarGridView();
        }

        protected void dropAdmFiltro_DataBound(object sender, EventArgs e)
        {
            dropAdmFiltro.Items.Insert(0, new ListItem("Escolha a Administração...", String.Empty));
        }

        protected void dropSetorFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarGridView();
        }

        protected void dropSetorFiltro_DataBound(object sender, EventArgs e)
        {
            dropSetorFiltro.Items.Insert(0, new ListItem("Escolha o Setor...", String.Empty));
        }

        protected void btnTrocarSenha_Click(object sender, EventArgs e)
        {
            try
            {
                MembershipUser user = Membership.GetUser(txtUsuario.Text.Trim());
                user.ChangePassword(txtOldPassword.Text.Trim(), txtPassword.Text.Trim());

                MessageWindow.MessageType = true;
                MessageWindow.Texto = "Senha Salva com Sucesso!";
                MessageWindow.ShowWindow();
            }
            catch (Exception)
            {

                MessageWindow.MessageType = false;
                MessageWindow.Texto = "Erro ao salvar a senha!";
                MessageWindow.ShowWindow();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Membership.DeleteUser(txtBuscarNome.Text);
        }

        protected void btnPasswordRetrieval_Click(object sender, EventArgs e)
        {
            try
            {
                MembershipUser usr = Membership.GetUser(txtUserNameRetrieval.Text.Trim());
                string resetPwd = usr.ResetPassword();

                usr.ChangePassword(resetPwd, txtNewPassword.Text.Trim());

                MessageWindow.MessageType = true;
                MessageWindow.Texto = "Senha substituída com sucesso!";
                MessageWindow.ShowWindow();
            }
            catch (Exception)
            {
                
                throw;
            }

        }


    }
}